package com.ys.erp.framework.handler.check;

import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.common.enums.RedisKey;
import com.ys.erp.framework.annotation.CheckAdminPermissions;
import com.ys.erp.framework.bean.dto.StageEmpDTO;
import com.ys.erp.framework.exception.YsException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author lwj
 * @date 2021/5/10
 */
@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class AdminPermissionHandler extends CheckAdminPermissionsHandler {

    private final RedisTemplate<String, String> redisTemplate;
    private static final Set<String> IGNORED_REQUEST_PATH = new HashSet<>();
    static {
        IGNORED_REQUEST_PATH.add("/stage/emp/login");
        IGNORED_REQUEST_PATH.add("//stage/emp/login");
        IGNORED_REQUEST_PATH.add("/pad/shop/login");
        IGNORED_REQUEST_PATH.add("//pad/shop/login");
    }
    @Override
    public void checkAdminPermission(HttpServletRequest request, CheckAdminPermissions permission) {
        String tokenFlag = "token";
        log.info(request.getRequestURI());
        if (IGNORED_REQUEST_PATH.contains(request.getRequestURI())) {
            return;
        }
        if (ObjectUtils.isEmpty(request.getHeader(tokenFlag))) {
            throw new YsException(-1, "权限错误");
        }
        String info = redisTemplate.opsForValue().get(RedisKey.Enums.EMP_LOGIN_FLAG.getKey() + request.getHeader(tokenFlag));
        //无效token
        if (ObjectUtils.isEmpty(info)) {
            throw new YsException(-1, "token失效");
        }
        JSONObject jsonObject = new JSONObject();
        // 循环遍历每个参数名称
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            jsonObject.put(paramName, paramValues);
        }
        log.info("请求接口：{}, 参数：{}", request.getRequestURI(), jsonObject.toJSONString());
        //当前用户的角色信息
        StageEmpDTO empDetailDTO = JSONObject.parseObject(info, StageEmpDTO.class);
        //当前用户的权限标识
        List<String> loginAdminRights = empDetailDTO.getRightFlags();
        //获取注解中表明需要的权限和角色
        if (ObjectUtils.isNotEmpty(permission.role())) {
            String annotationRole = permission.role();
            log.info("接口表明需要的角色:" + annotationRole);
            //校验角色
            if (ObjectUtils.isNotEmpty(annotationRole) && !empDetailDTO.getRoleName().equals(annotationRole)) {
                throw new YsException(-1, "权限不足");
            }
        }
        if (ObjectUtils.isNotEmpty(permission.right())) {
            List<String> annotationRights = Arrays.asList(permission.right().split(","));
            log.info("接口表明需要的权限:" + JSONObject.toJSONString(annotationRights));
            //校验权限
            if (ObjectUtils.isNotEmpty(annotationRights)) {
                //用户必须有标注中全部的权限
                if (permission.verifyAll() && !loginAdminRights.containsAll(annotationRights)) {
                    throw new YsException(-1, "权限不足");
                }
                //用户有标注的其中一个权限即可
                if (!permission.verifyAll() && Collections.disjoint(loginAdminRights, annotationRights)) {
                    throw new YsException(-1, "权限不足");
                }
            }
        }
    }

}
